from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from common.pagination import CustomerPagination
from system.models import Role
from system.serializer import RoleSerializer


class RoleViewSet(viewsets.ModelViewSet):
    # 指定序列化器类
    serializer_class = RoleSerializer
    # 指定权限类， 要求用户认证
    permission_classes = [IsAuthenticated]
    # 使用自定义分页
    pagination_class = CustomerPagination

    def role_list(self, request):
        name = request.GET.get('name', '')
        get_role = Role.objects.filter(name__contains=name).order_by('id')
        page_queryset = self.paginate_queryset(get_role)
        serializer = self.get_serializer(page_queryset, many=True)
        return self.get_paginated_response(serializer.data)

    @classmethod
    def role_add(cls, request):
        name = request.data.get('name', '')
        have_name = Role.objects.filter(name__contains=name)
        if have_name:
            return Response({
                'code': 500,
                'msg': '该角色已经存在'
            })
        dto = request.data
        _o = Role.objects.create(**dto)
        if _o:
            return Response({})
        else:
            return Response({'msg': '操作失败'})
